import React, { useState, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { AppState } from "../App";
import { DocumentTextIcon } from "@heroicons/react/solid";
import { FaLink, FaHandHoldingUsd } from "react-icons/fa";
import { ethers } from "ethers";
import axios from "axios";
import "../css/managerStyles.css";
import "../css/hualun.css";

const Creatforus = () => {
  const navigate = useNavigate();
  const App = useContext(AppState);
  const [target, setTarget] = useState("");
  const [description, setDescription] = useState("");
  const [photoHash, setPhotoHash] = useState("");
  const [selectedImage, setSelectedImage] = useState(null);
  const [selectedImageName, setSelectedImageName] = useState(null);
  const [showDeleteButton, setShowDeleteButton] = useState(false);
  const [showImage, setShowImage] = useState(false);
  const [loading, setLoading] = useState(false);
  const [title, setTitle] = useState("");
  const [moreDescription, setMoreDescription] = useState("");
  const [endTime, setEndTime] = useState("");
  const [errors, setErrors] = useState({});

  const validateForm = () => {
    let formErrors = {};
    if (!title) formErrors.title = "请选择慈善类别";
    if (!description) formErrors.description = "请输入筹款主题";
    if (!moreDescription) formErrors.moreDescription = "请输入筹款描述";
    if (!endTime) formErrors.endTime = "请选择截至时间";
    if (!target) formErrors.target = "请输入目标金额";
    if (!selectedImage) formErrors.selectedImage = "请上传图片";
    setErrors(formErrors);
    return Object.keys(formErrors).length === 0;
  };

  const handleImageChange = (e) => {
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      const reader = new FileReader();
      reader.onload = (readerEvent) => {
        setSelectedImage(readerEvent.target.result);
        setSelectedImageName(file.name);
        setShowImage(false);
        uploadImageToPinata(file);
      };
      reader.readAsDataURL(file);
    }
  };

  const uploadImageToPinata = async (file) => {
    setLoading(true);
    const formData = new FormData();
    formData.append("file", file);
    try {
      const response = await axios.post(
        "https://api.pinata.cloud/pinning/pinFileToIPFS",
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization:
             "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mb3JtYXRpb24iOnsiaWQiOiJjYjgzNmJjOS0xMjgzLTQwMWEtOWU4MS0wY2I5Y2ZkMjk1N2UiLCJlbWFpbCI6Imd1MDIwNDEyQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJwaW5fcG9saWN5Ijp7InJlZ2lvbnMiOlt7ImlkIjoiRlJBMSIsImRlc2lyZWRSZXBsaWNhdGlvbkNvdW50IjoxfSx7ImlkIjoiTllDMSIsImRlc2lyZWRSZXBsaWNhdGlvbkNvdW50IjoxfV0sInZlcnNpb24iOjF9LCJtZmFfZW5hYmxlZCI6ZmFsc2UsInN0YXR1cyI6IkFDVElWRSJ9LCJhdXRoZW50aWNhdGlvblR5cGUiOiJzY29wZWRLZXkiLCJzY29wZWRLZXlLZXkiOiJiZTNjOGVkY2IxZTA0MThkODlkMSIsInNjb3BlZEtleVNlY3JldCI6Ijc1OTVhY2JlY2E0MjU0YmM1ZGNlZTc3YTg2MTQwNGJkNGNjMmI0ZDM3ZGYwOTIwOTY0YjgxMzYzNjhhOGNiOGIiLCJpYXQiOjE3MTMxNTE2Nzh9.MgxXFGogmDXnIf6Z0U_qJlAuLcDxW3NFWwNr7u_u8Wc", // 替换为您的Pinata API密钥
          },
        }
      );
      setPhotoHash(response.data.IpfsHash);
    } catch (error) {
      console.error("Error uploading image to Pinata:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleMouseEnter = () => {
    setShowDeleteButton(true);
  };

  const handleMouseLeave = () => {
    setShowDeleteButton(false);
  };

  const handleDeleteImage = () => {
    setSelectedImage(null);
    setSelectedImageName(null);
    setPhotoHash("");
    const fileInput = document.getElementById("fileInput");
    if (fileInput) {
      fileInput.value = "";
    }
  };

  const handleImageClick = () => {
    setShowImage(!showImage);
  };

  const create = async () => {
    if (validateForm()) {
      try {
        if (!loading) {
          const startTimestamp = Math.floor(Date.now() / 1000); // 获取当前时间戳
          const tx = await App.Foundationcontract.createUserRequest(
            title,
            description,
            moreDescription,
            ethers.utils.parseUnits(target, 0),
            photoHash,
            Math.floor(new Date(endTime).getTime() / 1000), // 将日期转换为时间戳
            startTimestamp // 使用当前时间戳作为开始时间
          );
          await tx.wait();
          alert("创建成功!");
          setTitle("");
          setTarget("");
          setDescription("");
          setMoreDescription("");
          setEndTime("");
          setPhotoHash("");
          window.location.reload();
        }
      } catch (error) {
        const errorMsg = error.message;
        if (errorMsg.includes("User denied transaction signature")) {
          alert("用户拒绝了交易签名。");
        } else if (errorMsg.includes("Only manager can call this function")) {
          alert("只有管理员可以调用此函数");
        } else {
          console.log(errorMsg);
          alert("发生错误: " + errorMsg);
        }
      }
    } else {
      alert("请正确填写所有必填项");
    }
  };

  const back = async () => {
    navigate("/header/forus");
  };

  return (
    <div className="divFFF">
      <section>
        <div className="containerDiv">
          <div className="divFour">
            <h1>爱心筹款</h1>
            <div className="divFO">
              <div className="divP1">
                <div className="relative">
                  <FaLink className="input-icon" />
                  <select
                    value={title}
                    onChange={(e) => setTitle(e.target.value)}
                    className="category-select"
                  >
                    <option value="">选择慈善类别</option>
                    <option value="教育资助">教育资助</option>
                    <option value="慈善救助">慈善救助</option>
                    <option value="环境保护">环境保护</option>
                    <option value="社会福利">社会福利</option>
                    <option value="文化艺术">文化艺术</option>
                  </select>
                  {errors.title && <span className="error">{errors.title}</span>}
                </div>
              </div>
              <div className="divP1">
                <div className="relative">
                  <DocumentTextIcon className="input-icon" />
                  <input
                    placeholder="筹款主题"
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    id="message"
                    type="text"
                  />
                  {errors.description && (
                    <span className="error">{errors.description}</span>
                  )}
                </div>
              </div>
              <div className="divP1">
                <div className="relative">
                  <DocumentTextIcon className="input-icon" />
                  <input
                    placeholder="筹款描述"
                    value={moreDescription}
                    onChange={(e) => setMoreDescription(e.target.value)}
                    id="more-description"
                    type="text"
                  />
                  {errors.moreDescription && (
                    <span className="error">{errors.moreDescription}</span>
                  )}
                </div>
              </div>
              <div className="divP1">
                <div className="relative">
                  <DocumentTextIcon className="input-icon" />
                  <input
                    placeholder="截至时间 (YYYY-MM-DD)"
                    value={endTime}
                    onChange={(e) => setEndTime(e.target.value)}
                    id="end-time"
                    type="date"
                  />
                  {errors.endTime && (
                    <span className="error">{errors.endTime}</span>
                  )}
                </div>
              </div>
              <div className="divP1">
                <div className="relative">
                  <FaHandHoldingUsd className="input-icon" />
                  <input
                    placeholder="目标金额(WEI)"
                    value={target}
                    onChange={(e) => setTarget(e.target.value)}
                    type="number"
                  />
                  {errors.target && (
                    <span className="error">{errors.target}</span>
                  )}
                </div>
              </div>
              <div className="divP2">
                <div className="relative">
                  <FaLink className="img-icon" />
                  <input
                    type="file"
                    id="fileInput"
                    accept="image/*"
                    className="imgInput"
                    onChange={handleImageChange}
                  />
                  {errors.selectedImage && (
                    <span className="error">{errors.selectedImage}</span>
                  )}
                  {selectedImage && (
                    <>
                      <p onClick={handleImageClick}>
                        当前选择的图片: {selectedImageName}
                      </p>
                      <div
                        className="image-preview"
                        onMouseEnter={handleMouseEnter}
                        onMouseLeave={handleMouseLeave}
                      >
                        {showImage && (
                          <div className="image-preview">
                            <img src={selectedImage} alt="Preview" />
                            {showDeleteButton && (
                              <button
                                onClick={handleDeleteImage}
                                className="delete-button"
                              >
                                删除
                              </button>
                            )}
                          </div>
                        )}
                      </div>
                    </>
                  )}
                </div>
              </div>
              {loading && <div className="loading-circle"></div>}
              <div className="flex p-2 w-full">
                <button
                  onClick={create}
                  className="flex mx-auto text-white bg-yellow-500 border-0 py-2 px-8 focus:outline-none hover:bg-yellow-600 rounded text-lg"
                >
                  提交
                </button>
                <button
                  onClick={back}
                  className="flex mx-auto mx-2 text-white bg-yellow-500 border-0 py-2 px-8 focus:outline-none hover:bg-yellow-600 rounded text-lg"
                >
                  返回
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

export default Creatforus;
